﻿using System;
using System.Configuration;
using System.Diagnostics.Contracts;
using System.Web;
using NHibernate;
using OpenWaves.ActivityFeed.NHibernate;

namespace OpenWaves.ActivityFeed.Web.NHibernate
{
    public class NHibernateSessionPerRequestHttpModule : IHttpModule
    {
        public void Init(HttpApplication context)
        {
            context.BeginRequest += this.OnContextOnBeginRequest;
            context.EndRequest += this.OnContextOnEndRequest;
        }

        private void OnContextOnBeginRequest(object sender, EventArgs args)
        {
            //var factory = ServiceLocator.Resolve<INHibernateSessionFactory>();
            var sessionFactory = NHibernateActivityFeedSessionFactory.Current; //factory.CreateSessionFactory();
            var session = sessionFactory.OpenSession();
            session.FlushMode = FlushMode.Commit;
            var transaction = session.BeginTransaction();

            NHibernateSessionPerRequestProvider.CurrentSession = session;
            NHibernateSessionPerRequestProvider.CurrentTransaction = transaction;
        }

        private void OnContextOnEndRequest(object sender, EventArgs args)
        {
            if (NHibernateSessionPerRequestProvider.CurrentSession == null)
                return;

            if (HttpContext.Current.Error == null)
            {
                if (NHibernateSessionPerRequestProvider.CurrentSession.IsConnected)
                {
                    var currentTransaction = NHibernateSessionPerRequestProvider.CurrentTransaction;
                    if (currentTransaction != null && currentTransaction.IsActive)
                    {
                        currentTransaction.Commit();
                    }
                }
            }

            NHibernateSessionPerRequestProvider.CurrentSession.Dispose();
            NHibernateSessionPerRequestProvider.CurrentSession = null;
        }

        public void Dispose()
        {
        }
    }
}